package ishangchao.cn.haliaeetus

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.RelativeLayout
import com.kalemao.library.base.MResponse
import com.kalemao.library.custom.popupWindow.CommonPopupWindow
import com.kalemao.library.custom.stateful.StatefulLayout
import com.kalemao.library.http.BaseObserver
import com.kalemao.library.http.JsonUtils
import ishangchao.cn.haliaeetus.base.HaliaeetusActivity
import ishangchao.cn.haliaeetus.http.HttpNetWork
import ishangchao.cn.haliaeetus.login.event.MessageLoginEvent
import ishangchao.cn.haliaeetus.main.HomeFragment
import ishangchao.cn.haliaeetus.schedules.SchedulesFragment
import ishangchao.cn.haliaeetus.selfcenter.SelfCenterFragment
import ishangchao.cn.haliaeetus.selfcenter.event.MessageCardEvent
import ishangchao.cn.haliaeetus.selfcenter.event.MessageUserInfoEvent
import ishangchao.cn.haliaeetus.versions.MVersionsCheck
import ishangchao.cn.haliaeetus.versions.ViewVersionUpdate
import ishangchao.cn.haliaeetus.versions.ViewVersionUpdate.OnVersionUpdateListener
import kotlinx.android.synthetic.main.activity_main.navigation
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.find
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers


class MainActivity : HaliaeetusActivity() {

    private var homeFragment: HomeFragment? = null
    private var schedlesFragment: SchedulesFragment? = null
    private var selfCenterFragment: SelfCenterFragment? = null
    private var showFragmentPosition = 1
    private var mVersionsInfo: MVersionsCheck? = null
    private var mengban: View? = null
    private var mRootView: RelativeLayout? = null

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                showFragment(1)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                showFragment(2)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                showFragment(3)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun initViewEnd() {
        super.initViewEnd()
        EventBus.getDefault().register(this)
        Handler().postDelayed({ getVersionCheck() }, 500)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    // 显示第一个fragment
    private fun initFragment(position: Int, transaction: FragmentTransaction) {
        // 第一种方式（add），初始化fragment并添加到事务中，如果为null就new一个
        if (position == 1 && homeFragment == null) {
            homeFragment = HomeFragment()//.newInstance(strID)


            transaction.add(R.id.fra_act_mian_layout, homeFragment)
        }
        if (position == 2 && schedlesFragment == null) {

            schedlesFragment = SchedulesFragment()
            transaction.add(R.id.fra_act_mian_layout, schedlesFragment)
        }
        if (position == 3 && selfCenterFragment == null) {
            selfCenterFragment = SelfCenterFragment()
            transaction.add(R.id.fra_act_mian_layout, selfCenterFragment)
        }
    }

    private fun showFragment(position: Int) {
        showFragmentPosition = position
        val transaction = supportFragmentManager.beginTransaction()
        initFragment(position, transaction)
        hideFragment(transaction)
        transaction.show(getFragmentByIndex(position))
        transaction.commit()
        navigation.getMenu().getItem(position - 1).setChecked(true)
        if (position == 1) {
            homeFragment!!.onResume()
        } else if (position == 2) {
            schedlesFragment!!.onResume()
        } else if (position == 3) {
            selfCenterFragment!!.onResume()
        }
    }

    private fun getFragmentByIndex(index: Int): Fragment {
        if (index == 1) {
            return homeFragment!!
        } else if (index == 2) {
            return schedlesFragment!!
        } else if (index == 3) {
            return selfCenterFragment!!
        }
        return homeFragment!!
    }

    // 隐藏所有的fragment
    private fun hideFragment(transaction: FragmentTransaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment)
        }
        if (schedlesFragment != null) {
            transaction.hide(schedlesFragment)
        }
        if (selfCenterFragment != null) {
            transaction.hide(selfCenterFragment)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
        mengban = find(R.id.act_main_mengban)
        mRootView = find(R.id.lin_act_main_root)
        showFragment(1)
        showFullScreen(true)
    }

    override fun getContentViewLayoutID(): Int {
        return R.layout.activity_main
    }

    override fun setStatefulLayout(): StatefulLayout? {
        return null
    }

    private fun showFullScreen(full: Boolean) {
        if (full) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                    val window = window
                    val decorView = window.decorView
                    //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                    val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    decorView.systemUiVisibility = option
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                    window.statusBarColor = Color.TRANSPARENT
                } else {
                    val window = window
                    val attributes = window.attributes
                    val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    attributes.flags = attributes.flags or flagTranslucentStatus
                    window.attributes = attributes
                }
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    val window = window
                    val decorView = window.decorView
                    val option = View.SYSTEM_UI_FLAG_VISIBLE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    decorView.systemUiVisibility = option
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                    window.statusBarColor = resources.getColor(R.color.colorPrimary)
                } else {
                    val window = window
                    val attributes = window.attributes
                    val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    attributes.flags = attributes.flags and flagTranslucentStatus.inv()
                    window.attributes = attributes
                }
            }
        }
    }

    /**
     * 用户登录之后的回掉
     *
     * @author dim.
     * @time 2018/6/15 13:44.
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogined(event: MessageLoginEvent) {
        if (event != null && event.isLogin) {
            if (selfCenterFragment != null) {
                selfCenterFragment!!.logined()
            }
        }
    }

    /**
     * 用户修改个人信息之后的回掉
     *
     * @author dim.
     * @time 2018/6/15 13:44.
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onChangeInfo(event: MessageUserInfoEvent) {
        if (event != null) {
            if (selfCenterFragment != null) {
                selfCenterFragment!!.changeUserInfo(event)
            }
        }
    }

    /**
     * 用户修改银行卡信息之后的回掉
     *
     * @author dim.
     * @time 2018/6/15 14:13.
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onChangeCard(event: MessageCardEvent) {
        if (event != null) {
            if (selfCenterFragment != null) {
                selfCenterFragment!!.changeUserCard(event)
            }
        }
    }

    /**
     * 版本更新
     *
     * @author dim.
     * @time 2018/7/5 10:33.
     */
    private fun getVersionCheck() {
        HttpNetWork.getInstance().getHaliaeetusApi().getVersionsCheck().subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<MResponse>() {

                    override fun onError(e: Throwable) {
                        super.onError(e)
                    }

                    override fun onNext(mResponse: MResponse) {
                        mVersionsInfo = JsonUtils.fromJsonDate(mResponse.data,
                                MVersionsCheck::class.java)
                        needShowUpdate()
                    }
                })
    }

    /**
     * 是否需要加载下载更新界面
     *
     * @author dim.
     * @time 2018/7/5 10:40.
     */
    private fun needShowUpdate() {
        if (!mVersionsInfo!!.is_latested && popupWindowVersion == null) {
            showVersionUpdate(mVersionsInfo!!)
        }
    }

    var popupWindowVersion: CommonPopupWindow? = null
    /**
     * 显示版本更新的UI
     *
     * @author dim.
     * @time 2018/4/17 14:33.
     */
    private fun showVersionUpdate(versionInfo: MVersionsCheck) {
        versionInfo.update_desc = versionInfo.update_desc.replace("\\n", "\n")
        mengban!!.setOnClickListener({
            // 强制升级不能关闭
            if (!versionInfo.is_forced) {
                popupWindowVersion!!.dismiss()
            }
        })
        mengban!!.visibility = View.VISIBLE
        popupWindowVersion = CommonPopupWindow.Builder(this@MainActivity)
                .setView(ViewVersionUpdate(this, versionInfo, object : OnVersionUpdateListener {
                    override fun onViewClose() {
                        popupWindowVersion!!.dismiss()
                    }

                    override fun onDownloadSuccess() {
                        popupWindowVersion!!.dismiss()
                        exit()
                        this@MainActivity.finish()
                    }
                }))
                .setWidthAndHeight(resources.getDimension(R.dimen.dp_270).toInt(),
                        resources.getDimension(R.dimen.dp_345).toInt())
                .setAnimationStyle(R.style.AnimMiddle)
                .setOutsideTouchable(false)
                .setBackGroundLevel(0.5f)
                .create()
        popupWindowVersion!!.setOnDismissListener {
            popupWindowVersion = null
            mengban!!.visibility = View.GONE
        }
        popupWindowVersion!!.showAtLocation(mRootView, Gravity.CENTER, 0,
                0)
    }
}
